package concurrency;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import junit.framework.TestCase;

/**
 * 从任务中产生返回值
 *
 * @author fireway
 * @since 2019年 01月 20日 星期日 10:58:29 CST
 */
public class CallableTestCase extends TestCase {
    public void test() {
        ExecutorService exec = Executors.newCachedThreadPool();

        ArrayList<Future<String>> results = new ArrayList<Future<String>>();

        for(int i = 0; i < 10; i++) {
            TaskWithResult taskWithResult = new TaskWithResult(i);
            Future<String> future = exec.submit(taskWithResult);
            results.add(future);
        }

        for(Future<String> future : results) {
            try {
                // 当任务完成时，它具有一个结果，你可以调用
                // get()方法来获取该结果。
                // get() blocks until completion:
                System.out.println(future.get());
            } catch(InterruptedException e) {
                System.out.println(e);
                return;
            } catch(ExecutionException e) {
                System.out.println(e);
            } finally {
                exec.shutdown();
            }
        }
    }
}
